package support.filter;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;

import org.apache.commons.configuration.ConfigurationException;
import org.apache.commons.configuration.PropertiesConfiguration;
import org.apache.log4j.Logger;

import java.sql.*;

public class JdbcTestServlet extends HttpServlet {
	Logger logger = Logger.getLogger(JdbcTestServlet.class);
	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;

	/**
	 * Log.
	 */
	@Override
	public void init() throws ServletException {
		try {
			testJdbc();
		} catch (ConfigurationException e) {
			e.printStackTrace();
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		} catch (SQLException e) {
			e.printStackTrace();
		}
		super.init();
	}

	public void testJdbc() throws ClassNotFoundException, SQLException, ConfigurationException {
		PropertiesConfiguration p = new PropertiesConfiguration("datasource.properties");
		String className = p.getString("jdbc.driver");
		String url = p.getString("jdbc.url");
		String user = p.getString("jdbc.username");
		String pwd = p.getString("jdbc.password");

		Connection conn = null;
		Statement st = null;
		ResultSet rs = null;
		try {
			// 1.加载数据库驱动

			// 这里的是加载驱动，一般会写成如许：private String driverstr="com.mysql.jdbc.Driver"
			// Class.forName(driverstr);
			Class.forName(className);
			// 2.连接数据库
			conn = DriverManager.getConnection(url, user, pwd);
			// 3.创建语句
			st = conn.createStatement();
			// 4.履行查询
			rs = st.executeQuery("SELECT count(*) FROM information_schema.TABLES");
			// 5.处理惩罚成果
			if (!rs.wasNull()) {
				logger.info(" O(∩_∩)O ===> DataBase connection test successed!");
			} else {
				logger.info(" O(>_<)O ===> DataBase connection lost!");
			}
		}

		// 封闭数据源，开释资料，这里写的有点细，烦琐了点，然则如许会更能领会到封闭这些连接的细节，

		finally {
			// 6.开释资料
			try {
				if (rs != null) {
					rs.close();
				}
			} catch (Exception e) {
				e.printStackTrace();
			}

			try {
				if (st != null) {
					st.close();
				}
			} catch (Exception e) {
			}
			try {
				if (conn != null) {
					conn.close();
				}
			} catch (Exception e) {
			}

		}
	}

}
